package com.steven.ourcontest.forum.view

import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.util.Log
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.daimajia.numberprogressbar.NumberProgressBar
import com.steven.ourcontest.R
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.base.DialogBuilder
import com.steven.ourcontest.forum.viewmodel.AddForumViewModel
import com.steven.ourcontest.net.EmptyResponse
import com.steven.ourcontest.net.FileRequestBody
import com.steven.ourcontest.net.NetConstants
import com.steven.ourcontest.net.RetrofitCallback
import com.steven.ourcontest.utils.DensityUtil
import com.steven.ourcontest.utils.ScreenUtils
import com.steven.ourcontest.utils.changed
import com.steven.ourcontest.utils.openAlbum
import com.steven.ourcontest.utils.toast
import id.zelory.compressor.Compressor
import kotlinx.android.synthetic.main.activity_write_forum.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class WriteForumActivity : BaseActivity() {

    private val addForumViewModel: AddForumViewModel by viewModels()
    private val picPathArray = ArrayList<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun getStatusBarColor(): Int {
        return R.color.white
    }

    override fun getViewId(): Int? {
        return R.layout.activity_write_forum
    }

    override fun initView() {
        val layoutParams = iv_add_picture?.layoutParams
        DensityUtil.dp2px(this, 24f).let { dp ->
            layoutParams?.width = (ScreenUtils.getScreenWidth(this) - dp) / 3 - dp / 3
            layoutParams?.height = layoutParams?.width
        }
        iv_add_picture?.layoutParams = layoutParams
        iv_add_picture?.setOnClickListener {
            openAlbum(this)
        }
        addForumViewModel.addResponse.observe(this, Observer {
            if (it?.msg == "success") {
                finish()
                toast("发布成功！")
            } else {
                toast(it?.msg.toString())
            }
        })
        tv_confirm?.setOnClickListener {
            val title = et_title?.text
            val content = et_content?.text
            if (!checkText(title)) {
                return@setOnClickListener
            }
            if (!checkText(content)) {
                return@setOnClickListener
            }
            val dialog = DialogBuilder(this)
                .setCancelable(false)
                .build(R.layout.dialog_upload)
            dialog.show()
            val progressView = dialog.findViewById<NumberProgressBar>(R.id.progress)
            GlobalScope.launch(Dispatchers.Default) {
                val body = MultipartBody.Builder()
                picPathArray.forEach {
                    val file = File(it)
                    val resFile = Compressor.compress(this@WriteForumActivity, file)
                    val fileRQ = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        resFile
                    )
                    body.addFormDataPart("images", resFile.name, fileRQ)
                }
                body.addFormDataPart("title", title.toString()).addFormDataPart("content", content.toString())
                val realBody = FileRequestBody(body.build(), object : RetrofitCallback<EmptyResponse>() {
                    override fun onLoading(total: Long, progress: Long) {
                        GlobalScope.launch(Dispatchers.Main) {
                            super.onLoading(total, progress)
                            progressView.progress =
                                ((progress / total.toFloat()) * 100).toInt()
                            if (total == progress) {
                                dialog.dismiss()
                            }
                        }
                    }
                })
                addForumViewModel.addForum(realBody, {}, {})
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            1 -> {
                val cursor: Cursor? = data?.data?.let {
                    contentResolver?.query(
                        it,
                        arrayOf(MediaStore.Images.Media.DATA),
                        null,
                        null,
                        null
                    )
                }
                cursor?.moveToFirst()
                val path = cursor?.getString(
                    cursor.getColumnIndex(
                        MediaStore.Images.Media.DATA
                    )
                ) ?: ""
                cursor?.close()
                try {
                    if (path == "") {
                        throw Exception("file path is error")
                    }
                    picPathArray.add(path)
                    val imageView = ImageView(this)
                    val layoutParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                    DensityUtil.dp2px(this, 24f).let { dp ->
                        layoutParams.width = (ScreenUtils.getScreenWidth(this) - dp) / 3 - dp / 3
                        layoutParams.height = layoutParams.width
                        layoutParams.marginStart = dp / 6
                        layoutParams.marginEnd = dp / 6
                        layoutParams.topMargin = dp / 6
                        layoutParams.bottomMargin = dp / 6
                    }
                    imageView.layoutParams = layoutParams
                    imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                    val viewAt = flex_container.indexOfChild(iv_add_picture)
                    flex_container?.addView(imageView, viewAt)
                    Glide.with(this)
                        .load(path)
                        .placeholder(R.drawable.ic_placeholder)
                        .dontAnimate()
                        .error(R.drawable.aio_image_fail)
                        .into(imageView)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun checkText(text: Editable?): Boolean {
        //懒得改了
        if (text.isNullOrEmpty()) {
            toast("文本不能为空")
            return false
        }
        return true
    }
}